<?php


namespace app\api\wxpay;

class JsApi
{
	public $WechatPaySdk;
	public function __construct($config)
	{
		$this->WechatPaySdk = new WechatPaySdk($config);
	}
	public function pay($out_trade_no, $amount, $description, $notify_url, $openid)
	{
		$amount = $amount * 100;
		$instance = $this->WechatPaySdk->instance();
		try {
			$resp = $instance->chain("/v3/pay/transactions/jsapi")->post(["json" => ["appid" => \strval($this->WechatPaySdk->appid), "mchid" => \strval($this->WechatPaySdk->merchant_id), "description" => \strval($description), "out_trade_no" => \strval($out_trade_no), "notify_url" => \strval($notify_url), "amount" => ["total" => \intval($amount)], "payer" => ["openid" => \strval($openid)]], "debug" => false]);
			$result = json_decode($resp->getBody(), true);
			$merchantPrivateKeyFilePath = "file://" . $this->WechatPaySdk->merchantPrivateKeyFilePath;
			$merchantPrivateKeyInstance = \WeChatPay\Crypto\Rsa::from($merchantPrivateKeyFilePath);
			$params = ["appId" => $this->WechatPaySdk->appid, "timeStamp" => \strval(\WeChatPay\Formatter::timestamp()), "nonceStr" => \WeChatPay\Formatter::nonce(), "package" => "prepay_id=" . $result["prepay_id"]];
			$params += ["paySign" => \WeChatPay\Crypto\Rsa::sign(\WeChatPay\Formatter::joinedByLineFeed(...array_values($params)), $merchantPrivateKeyInstance), "signType" => "RSA"];
			return $params;
		} catch (\Exception $e) {
			if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
				$r = $e->getResponse();
				return $r->getBody();
			}
			return $e->getMessage();
		}
	}
}